package com.xbx.zuul.utils;

import com.xbx.baseweb.model.User;
import com.xbx.common.constant.GlobalConstant;
import com.xbx.zuul.auth.MyShiroCasRealm;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 用户工具类
 *
 * @author 89005691
 * @create 2018-08-31 12:21
 */
@Component
@Slf4j
public class UserUtlis {

    private static String active;

    @Value("${spring.profiles.active}")
    public void setActive(String active) {

        this.active = active;
    }

    /**
     * 获取已登录的用户信息
     *
     * @return
     */
    public static User getLoginUserInfo() {

        Object object = null;

        try {

            object = SecurityUtils.getSubject().getSession().getAttribute(GlobalConstant.GLOBAL_USER_INFO);

            if (active.equals("dev")) {

                object = new User();

                ((User) object).setId(1L);
                ((User) object).setUsername("197370");
                ((User) object).setSysUsername("hufeng");
            }
        } catch (Exception e) {

            log.error("获取用户信息出错", e);
            return null;
        }

        return object == null ? null : (User) object;
    }

    /**
     * 清空权限缓存
     */
    public static void clearShiroCache() {

        RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
        MyShiroCasRealm realm = (MyShiroCasRealm) rsm.getRealms().iterator().next();
        realm.clearCachedAuthorization();
    }

    /**
     * 清空权限缓存
     */
    public static void logout() {

        Subject subject = SecurityUtils.getSubject();

        subject.logout();
    }
}
